let getTreeCheckedId, uncheckedTree
function createTree (datas, treeWrap, selectAll) {
  let html = ''
  html += '<div class="layui-container"><div class="tree-list-wrap" id="tree1"></div><div class="tree-list-wrap" id="tree2"></div><div class="tree-list-wrap" id="tree3"></div><div class="tree-checked-wrap"><div class="checked-tree-wrap" id="tree4"></div></div></div>'

  $(treeWrap).html(html)

  var baseData = [
    {
      id: 0,
      title: '内部',
      arryName: 'innerList',
      nextArry: formatCompanyData(datas.innerList)
    },
    {
      id: 1,
      title: '外部',
      arryName: 'outerList',
      children: [
        {
          id: 2,
          title: '好友公司',
          arryName: 'friendList',
          nextArry: formatCompanyData(datas.outerList.friendList)
        },
        {
          id: 3,
          title: '客商',
          arryName: 'customerList',
          nextArry: formatCustomerData(datas.outerList.customerList)
        },
        {
          id: 4,
          title: '供应商',
          arryName: '',
        }
      ]
    }
  ]

  layui.use(function(){
    var layer = layui.layer
    ,form = layui.form
    ,laypage = layui.laypage
    ,element = layui.element
    ,laydate = layui.laydate
    ,tree = layui.tree
    ,util = layui.util;
  
  

  var baseData = [
          { id: 0,
            title:'内部',
            arryName:'innerList',
            nextArry:formatCompanyData(datas.innerList)
          },
          { id: 1,
            title:'外部',
            arryName:'outerList',
            children:[
              { id: 2,
                title:'好友公司',
                arryName:'friendList',
                nextArry:formatCompanyData(datas.outerList.friendList)
              },
              { id: 3,
                title:'客商',
                arryName:'customerList',
                nextArry:formatCustomerData(datas.outerList.customerList)
              },
              { id: 4,
                title:'供应商',
                arryName:'',
              }
            ]
          }
        ]
  
    tree.render({
        elem: '#tree1',  //绑定元素
        showCheckbox:true,
        onlyIconControl:true,
        data:baseData,
        id: 'demoId1',
        click:function(obj){
          if($('#tree3').children().length){
            // tree.reload('demoId3', {data:[]});
          }
          // 二级树
          if(obj?.data?.nextArry){
            Object.keys(obj.data.nextArry).forEach(item=>{
              obj.data.nextArry[item].spread = true
              obj.data.nextArry[item].pid = obj.data.id // 子集赋予父id
              if(obj.data.nextArry[item].children){ 
                obj.data.nextArry[item].children.forEach(items=>{
                  items.rootId = obj.data.id
                })
              }
            })
          }
  
          renderTree2(obj.data.nextArry)
        },
      oncheck: function(obj){
        if($('#tree3').children().length){
          tree.reload('demoId3', {data:[]});
        }
        let nextArry = []
        obj.checked ? obj.data.checked = true : obj.data.checked = false 
        // 当前树
        if(obj?.data?.children?.length){
          obj.data.children.forEach(item=>{ // 给子集赋值方便后面使用
            obj.checked ? item.checked = true : item.checked = false
            if(item.nextArry){
              Object.keys(item.nextArry).forEach(items=>{
                if(obj.checked){
                  item.nextArry[items].checked = true
                }else{
                  item.nextArry[items].checked = false
                }
              })
            }
          })
        }
  
  
        // 下级树 （部分需要写成递归）
        if(obj?.data?.nextArry){
          Object.keys(obj.data.nextArry).forEach(item=>{
            // 有子项的不能直接设置checked !obj.data.nextArry[item].children.length
            if(obj.checked && !obj.data.nextArry[item]?.children?.length){
              obj.data.nextArry[item].checked = true
            }else{
              obj.data.nextArry[item].checked = false
              // 如果有子集把所有子集设置选中  （只局限一组数据，根据需求变动下）
              if(obj.data.nextArry[item].children){ 
                obj.data.nextArry[item].children.forEach(item=>{
                  obj.checked?item.checked = true:item.checked = false
                  obj.rootId = obj.data.id
                })
              }
            }
  
            obj.data.nextArry[item].pid = obj.data.id // 子集赋予父id
            if(obj.data.nextArry[item].children){ 
                obj.data.nextArry[item].children.forEach(items=>{
                  items.rootId = obj.data.id
                })
            }
            nextArry.push(obj.data.nextArry[item])
          })
        }
  
        // 对比当前选择和二级树是否为父子级关系 如果是刷新二级树数据
        let tree2Data = $('#tree2').find('input[type="checkbox"]').val()
        let isParent = nextArry.some(item=>{return item.id === tree2Data})
        if(isParent){ // 如过是所属关系刷新数据
          renderTree2(obj.data.nextArry)
        }
          const checketList = getCheckedList()
          console.log(checketList)
      }
    })
  
  
    function renderTree2(itemData){
      let data = []
      if(!itemData){
        itemData = []
      }
      Object.keys(itemData).forEach(item=>{
        data.push(itemData[item])
      })
  
      tree.render({
        elem: '#tree2',  //绑定元素
        showCheckbox:true,
        onlyIconControl:true,
        data:data,
        id: 'demoId2',
        click: function(obj){
          console.log(baseData)
          // 三级树
          if(obj?.data?.childrens?.length){
            obj.data.childrens.forEach(item=>{
              item.spread = true
              item.rootId = obj.data.rootId
              item.pid = obj.data.id // 子集赋予父id
              if(item.childrens){
                item.childrens.forEach(items=>{
                  items.rootId = obj.data.rootId
                })
              }
            })
          }
          renderTree3(obj.data)
        },
        oncheck: function(obj){
          obj.checked ? obj.data.checked = true : obj.data.checked = false 
  
          let tree2CheckArry = []
          let tree2CheckN = $('#tree2').find('input[type="checkbox"]')
          for(let i=0; i<tree2CheckN.length;i++){
            tree2CheckArry.push($(tree2CheckN[i]).prop('checked'))
          }
          
          // 检测是否全部取消选中 去取消一级树选中
          let noParentCheck = tree2CheckArry.every(item=>{return !item})
          let isParentCheck = tree2CheckArry.every(item=>{return item})
  
          // 父节点操作
          // let nodeId = obj.data.rootId ? obj.data.rootId : obj.data.pid
          let setNode = checkedParentNode(obj.data.pid??obj.data.rootId)
          let tree2AllvalNode
          if($('#tree2 .layui-tree-pack').length){
            tree2AllvalNode = $('#tree2 .layui-tree-pack').find('input')
          }else{
            tree2AllvalNode =  $('#tree2').find('input')
          }
  
          let tree2AllvalArry = []
  
          setTimeout(()=>{
            for(let j =0; j<tree2AllvalNode.length;j++){
              tree2AllvalArry.push($(tree2AllvalNode[j]).prop('checked'))
            }
            let noallCheck = tree2AllvalArry.some(item1=>{return !item1})
            let isallCheck = tree2AllvalArry.some(item1=>{return item1})
            let allCheckTree2 = tree2AllvalArry.every(item1=>{return item1===true})
            let hasHalf = $('#tree2 .layui-tree-pack').find('.layui-form-half-checked').length
  
  
            if((isallCheck&&noallCheck&&!allCheckTree2) || hasHalf){
              if($('#tree2 .layui-tree-pack').length){
               $('#tree2 .layui-tree-set').find('input').eq(0).prop('checked',false).next().addClass('layui-form-half-checked')
               }
               setNode.prop('checked',false).next().addClass('layui-form-half-checked')
            }else{
              if(allCheckTree2){
                if(obj?.data?.children?.length){
                $('#tree2 .layui-tree-set').find('input').eq(0).prop('checked',true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
                }
                setNode.prop('checked',true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
              }
            }
          })
  
  
  
          
          if(noParentCheck){ // 全部取消
            if(setNode.prop('checked')){
              setNode.next().click()
            }
          }
  
          if(isParentCheck){ // 全部选中
            if(!setNode.prop('checked')){ 
              setNode.next().click()
            }
          }
  
  
          // 操作3级
          let nextArry = []
          if(obj?.data?.childrens){
            obj.data.childrens.forEach(item=>{
            obj.checked ? item.checked = true : item.checked = false
            item.spread = true
          })
          }
          
  
  
            // 下级树 （部分需要写成递归）
        if(obj?.data?.childrens){
          Object.keys(obj.data.childrens).forEach(item=>{
            // 有子项的不能直接设置checked !obj.data.nextArry[item].children.length
            if(obj.checked && !obj.data.childrens[item]?.children?.length){
              obj.data.childrens[item].checked = true
            }else{
              obj.data.childrens[item].checked = false
              // 如果有子集把所有子集设置选中  （只局限一组数据，根据需求变动下）
              if(obj.data.childrens[item].children){ 
                obj.data.childrens[item].childrens.forEach(item=>{
                  obj.checked?item.checked = true:item.checked = false
                  // obj.rootId = obj.data.id
                })
              }
            }
  
            obj.data.childrens[item].pid = obj.data.id // 子集赋予父id
            nextArry.push(obj.data.childrens[item])
          })
        }
  
          // 对比当前选择和三级级树是否为父子级关系 如果是刷新三级树数据
          let tree3Data = $('#tree3').find('input[type="checkbox"]').val()
          let isParent = nextArry.some(item=>{return item.id === tree3Data})
          if(isParent){ // 如过是所属关系刷新数据
            renderTree3(obj.data)
          }
          const checketList = getCheckedList()
          console.log(checketList)
        }
      })
    }
  
    function renderTree3(data){
      if(!data){return}
      let datas = formatDepartmentData(data.childrens)
      tree.render({
        elem: '#tree3',  //绑定元素
        showCheckbox:true,
        data: datas,
        id: 'demoId3',
        click: function(obj){
          console.log(getCheckedId())
        },
        oncheck: function(obj){
          obj.checked ? obj.data.checked = true : obj.data.checked = false 
  
          let tree3CheckArry = []
          let tree3CheckN = $('#tree3').find('input[type="checkbox"]')
          for(let i=0; i<tree3CheckN.length;i++){
            tree3CheckArry.push($(tree3CheckN[i]).prop('checked'))
          }
  
          // 检测是否全部取消选中 去取消二级树选中
          let noParentCheck = tree3CheckArry.every(item=>{return !item})
          let isParentCheck = tree3CheckArry.every(item=>{return item})
          
          // 不为全选
          let halfParentCheck = tree3CheckArry.some(item=>{return !item})
  
          // 父节点操作
          let setNode1 = checkedParentNode(obj.data.rootId)
          
          let setNode = checkedParentNode(obj.data.pid)
          let tree2AllvalNode = $('#tree2 .layui-tree-pack').find('input')
          let tree2AllvalArry = []
          
          setTimeout(()=>{
            for(let j =0; j<tree2AllvalNode.length;j++){
              tree2AllvalArry.push($(tree2AllvalNode[j]).prop('checked'))
            }
            let noallCheck = tree2AllvalArry.some(item1=>{return !item1})
            let isallCheck = tree2AllvalArry.some(item1=>{return item1})
            let allCheckTree2 = tree2AllvalArry.every(item1=>{return item1})
            let hasHalf = $('#tree2 .layui-tree-pack').find('.layui-form-half-checked').length
  
  
            if((isallCheck&&noallCheck&&!allCheckTree2) || hasHalf){
               $('#tree2 .layui-tree-set').find('input').eq(0).prop('checked',false).next().addClass('layui-form-half-checked')
               setNode1.prop('checked',false).next().addClass('layui-form-half-checked')
            }else{
              if(allCheckTree2){
                $('#tree2 .layui-tree-set').find('input').eq(0).prop('checked',true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
                setNode1.prop('checked',true).next().removeClass('layui-form-half-checked').addClass('layui-form-checked')
              }
            }
          })
          
  
  
          if(halfParentCheck ){
            if(!noParentCheck){
              setNode.next().addClass('layui-form-half-checked')
              setNode.prop('checked',false)
              setNode1.next().addClass('layui-form-half-checked')
              setNode1.prop('checked',false)
            }else{
            setNode.prop('checked',true)
            setNode.next().addClass('layui-form-checked')
            setNode.next().removeClass('layui-form-half-checked')
            setNode1.prop('checked',true)
            setNode1.next().addClass('layui-form-checked')
            setNode1.next().removeClass('layui-form-half-checked')
            }
          }  
            
          
          
          if(noParentCheck){ // 全部取消
            if(setNode.prop('checked')){
              setNode.next().click()
            }
          }
  
          if(isParentCheck){ // 全部选中
              if(obj.data.pid!=='100016'){
                if(!setNode.prop('checked')){ 
                // setNode.next().click()
                data.checked = true
                console.log(baseData)
                setNode.prop('checked',true)
                setNode.next().addClass('layui-form-checked')
                setNode.next().removeClass('layui-form-half-checked')
              }
            }
          }
          // console.log(obj.data); //得到当前点击的节点数据
          // console.log(obj.checked); //得到当前节点的展开状态：open、close、normal
          // console.log(obj.elem); //得到当前节点元素
          const checketList = getCheckedList()
          console.log(checketList)
        }
      })
    }
  
  
  
    // function setChecked(data){
    //   let dataList
    //   if(data.hasOwnProperty('children' && ddata.children.length > 0)){
    //     dataList = data
    //   } else if (data.hasOwnProperty('childrens' && ddata.children.length > 0)) {
    //     dataList = data
    //   } else if (data.hasOwnProperty('nextArry' && ddata.children.length > 0)) {
        
    //   }
  
    // }
  
  
  
  
  
  
  function formatDepartmentData (data, isChecked) {
    let arr = []
    data.map(obj => {
      if (obj.type !== 'company') {
        // obj.checked = isChecked
        if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
          obj.children = obj.childrens
          formatDepartmentData(obj.childrens, isChecked)
        }
        arr.push(obj)
      }
    })
    return arr
  }
  
  function checkedParentNode(id){
    return $('#treeWrap').find('input[value="'+id+'"]')
  }
  
  
  function getCheckedList (data = baseData, arr = []) {
    data.map(obj => {
      if (obj.checked) {
        arr.push(obj)
      } else{
        let dataList = []
  
        if(obj.hasOwnProperty('children') && obj.children.length > 0){
          dataList = obj.children
        } else if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
          dataList = obj.childrens
        } else if (obj.hasOwnProperty('nextArry') && Object.values(obj.nextArry).length > 0) {
          dataList = Object.values(obj.nextArry)
        }
        getCheckedList(dataList, arr)
      }
    })
    return arr
  }
  
  function getCheckedId (data = baseData, arr = []) {
    data.map(obj => {
      if (obj.checked) {
        arr.push(obj.id)
      }
      let dataList = []
  
      if(obj.hasOwnProperty('children') && obj.children.length > 0){
        dataList = obj.children
      } else if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
        dataList = obj.childrens
      } else if (obj.hasOwnProperty('nextArry') && Object.values(obj.nextArry).length > 0) {
        dataList = Object.values(obj.nextArry)
      }
      getCheckedId(dataList, arr)
    })
    return arr
  }
  
  
  
  
  
    
    //欢迎信息
    // layer.msg('Hello World');
    
    //输出版本号
    lay('#version').html(layui.v);
    
    //日期
    laydate.render({
      elem: '#test2'
      ,value: new Date()
      ,isInitValue: true
    });
    
    //触发事件
    util.event('test-active', {
      'test-form': function(){
        layer.open({
          type: 1
          ,resize: false
          ,shadeClose: true
          ,area: '350px'
          ,title: 'layer + form'
          ,content: ['<ul class="layui-form layui-form-pane" style="margin: 15px;">'
            ,'<li class="layui-form-item">'
              ,'<label class="layui-form-label">输入框</label>'
              ,'<div class="layui-input-block">'
                ,'<input class="layui-input" lay-verify="required" name="field1">'
              ,'</div>'
            ,'</li>'
            ,'<li class="layui-form-item">'
              ,'<label class="layui-form-label">选择框</label>'
              ,'<div class="layui-input-block">'
                ,'<select name="field2">'
                  ,'<option value="A">A</option>'
                  ,'<option value="B">B</option>'
                ,'<select>'
              ,'</div>'
            ,'</li>'
            ,'<li class="layui-form-item" style="text-align:center;">'
              ,'<button type="submit" lay-submit lay-filter="*" class="layui-btn">提交</button>'
            ,'</li>'
          ,'</ul>'].join('')
          ,success: function(layero, index){
            layero.find('.layui-layer-content').css('overflow', 'visible');
            
            form.render().on('submit(*)', function(data){
              layer.msg(JSON.stringify(data.field), {icon: 1});
              //layer.close(index); //关闭层
            });
          }
        });
      }
    });
  });

  function getCheckedId (data = baseData, arr = []) {
    data.map(obj => {
      if (obj.checked) {
        arr.push(obj.id)
      }
      let dataList = []

      if (obj.hasOwnProperty('children') && obj.children.length > 0) {
        dataList = obj.children
      } else if (obj.hasOwnProperty('childrens') && obj.childrens.length > 0) {
        dataList = obj.childrens
      } else if (obj.hasOwnProperty('nextArry') && Object.values(obj.nextArry).length > 0) {
        dataList = Object.values(obj.nextArry)
      }
      getCheckedId(dataList, arr)
    })
    return arr
  }

  function createCheckedDom (list) {
    let html = ''

    list.map(obj => {
      html += `<div class="tree-checked-list" data-id="${obj.id}"><p>${obj.title}</p><i class="layui-icon layui-icon-close" onclick="uncheckedTree(this)"></i></div>`
    })

    $('#tree4').html(html)
  }

  getTreeCheckedId = getCheckedId
}

function formatCompanyData (data, t, id = 0) {
  Object.keys(data).map(k => {
    data[k].ftype = t
    data[k].name ? data[k].title = data[k].name : ''
    data[k].pid = id
    if (data[k].hasOwnProperty('children') && Object.keys(data[k].children).length > 0) {
      formatCompanyData(data[k].children, t, data[k].id)

      data[k].childrens = Object.values(data[k].children)
      if (data[k].type === 'company' || data[k].type === 'customer') {
        let arr = []
        Object.values(data[k].children).map(obj => {
          if (obj.type === 'company' || obj.type === 'customer') {
            arr.push(obj)
          }
        })
        data[k].children = arr
      }
    }
  })
  return Object.values(data)
}

function formatCustomerData (data, t, id) {
  let arr = []
  Object.values(data).map(obj => {
    obj.ftype = t
    obj.pid = id
    obj.title = obj.name
    arr.push(obj)
  })
  return arr
}